/**
 * 简单的文件上传服务器
 */
var http = require('http'),
    util = require('util'),
    url = require('url'),
    formidable = require('formidable'),
    fs = require('fs');
var dir = "./tempupload";
//创建上传目录
fs.exists(dir,function(exists){
    if(!exists){
        fs.mkdir(dir, function(err){
            if(err) throw err;
        });
    }
})

var server = http.createServer(function(req, res) {
    if (isFormData(req)) {
        var form = new formidable.IncomingForm();
        form.uploadDir = dir;
        form.parse(req, function(err, fields, files) {
            if(err){
                res.writeHead(500,{
                    'content-type': 'text/plain'
                });
                res.end('Invalid server error');
                return;
            }
            res.writeHead(200, {
                'content-type': 'text/plain'
            });
            res.write('received upload:\n\n');
            res.end(util.inspect({
                fields: fields,
                files: files
            }));
        });
        form.on('progress',function(byteReceived,bytesExpected){
            console.log("上传进度:"+Math.floor(byteReceived*1.0/bytesExpected*100));
        });
    } else {
        outputForm(req, res);
    }
});

server.listen(4090,function(err){
    if(!err){
        console.log('server start on port 4090');
    }
});

function isFormData(req) {
    var type = req.headers['content-type'] || '';
    if (url.parse(req.url).pathname === '/upload'&&req.method.toLowerCase() === 'post' && type.indexOf('multipart/form-data') != -1) {
        return true;
    }
    return false;
}

function outputForm(req, res) {
    res.writeHead(200, {
        'content-type': 'text/html'
    });
    res.end('<form action="http://127.0.0.1:8888/upload/normal" enctype="multipart/form-data" method="post">' +'name: <input type="text" name="name"><br>'+ 'uuid: <input type="text" name="uuid"><br>' + '<input type="file" name="upload" multiple="multiple"><br>' + '<input type="submit" value="Upload">' + '</form>');
}